package com.example.qr;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

/**
 * This class is a collection of functions useful to process a bitmap image.
 * 
 * Most of the functions here focus on compression or otherwise make the image more compact.
 * 
 * More specifically, one is free to add functions
 */

public class CustomBitmapFactory {
	
	/**
	 * Creates a bitmap image from the file system, denoted by the image file path.
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 */
	public static Bitmap bitmapFromFile(String path) throws FileNotFoundException {
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		if (bitmap == null) {
			throw new FileNotFoundException("Couldn't open " + path);
		}
		return bitmap;
	}

	/**
	 * Scales the bitmap image to the specified dimension.
	 * @param src The bitmap to scale.
	 * @param width The width of the image
	 * @param height The height of the image
	 * @return
	 */
	public static Bitmap scaleBitmapTo(Bitmap src, int width, int height) {
		Bitmap bitmap = Bitmap.createScaledBitmap(src, width, height, false);
		src.recycle();
		src = null;
		return bitmap;
	}
	/**
	 * Scales the bitmap image by a factor.
	 * @param src The bitmap to scale.
	 * @param factor The decimal value to scale the bitmap by.
	 * @return
	 */
	public static Bitmap scaleBitmapTo(Bitmap src, double factor) {
		//TODO Add sanity check to the factor parameter, such as a factor of <0 or overly large factor.
		int width = src.getWidth();
		int height = src.getHeight();
		Bitmap bitmap = Bitmap.createScaledBitmap(src, (int) (width* factor), (int) (height * factor), false);
		src.recycle();
		src = null;
		return bitmap;
	}

	/**
	 * 
	 * A factory method that compresses the image by lossy conversion.
	 * @param src The bitmap to compress.
	 * @param format CompressFormat.JPEG, PNG, or WEBP. The image format to compress as.
	 * @param percent 0-100. 100 means as lossless as possible, 
	 * 					while 0 denotes compress as much as possible at the expense of losing data.
	 * @return
	 */
	public static Bitmap compressBitmap(Bitmap src, CompressFormat format, int percent) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream() ;
		src.compress(CompressFormat.JPEG, percent, stream) ;
		byte[] byteArray = stream.toByteArray();
		Bitmap res = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
		src.recycle();
		src = null;
		return res;
	}

}
